package com.bytz.modules.cms.order.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bytz.modules.cms.c4c.model.C4cGetContacts;
import com.bytz.modules.cms.c4c.model.C4cResponse;
import com.bytz.modules.cms.c4c.model.C4cSalesQuote;
import com.bytz.modules.cms.c4c.model.C4cY2OrY3Sales;
import com.bytz.modules.cms.c4c.service.IC4cFeignService;
import com.bytz.modules.cms.c4c.sync.C4cOdataFeign;
import com.bytz.modules.cms.order.constant.OrderConstants;
import com.bytz.modules.cms.order.entity.Order;
import com.bytz.modules.cms.order.entity.OrderItem;
import com.bytz.modules.cms.order.service.IOrderItemService;
import com.bytz.modules.cms.order.service.IOrderService;
import com.bytz.modules.cms.order.service.ISalesQuoteService;
import com.bytz.modules.cms.reseller.entity.EndUser;
import com.bytz.modules.cms.reseller.service.IEndUserService;
import com.bytz.modules.cms.user.service.ICmsSysUserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Optional;

@Service
@Slf4j
@AllArgsConstructor
public class SalesQuoteServiceImpl implements ISalesQuoteService {


    private final IC4cFeignService c4cService;
    private final C4cOdataFeign c4cOdataFeign;
    private final ICmsSysUserService sysUserService;
    private final IEndUserService endUserService;
    private final IOrderItemService itemService;
    private final IOrderService orderService;

    @Override
    public void salesQuote(Order order) {
        C4cSalesQuote salesQuote = createSalesQuote(order);
        try{
            // 创建产品行
            c4cService.createProduct(salesQuote.getObjectId());
        }catch (Exception e){
            log.error("创建产品行失败，orderId：" +order.getId(), e);
        }
        try{
            // 如果为项目订单（并且机会不为空）则将机会和报价表关联
            if (OrderConstants.OrderType.PROJECT.equals(order.getOrderType()) && StringUtils.isNotBlank(order.getOpportunityId()) && StringUtils.isNotBlank(order.getOpportunityObjectId()) ) {
                c4cService.relationQuoteOpportunity(salesQuote.getObjectId(), order.getOpportunityId());
                // 将机会更新为赢单
                c4cService.updateOpportunityProbability(order.getOpportunityObjectId());
            }
        }catch (Exception e){
            log.error("关联项目订单和机会失败，orderId：" + order.getId(), e);
        }

        try{
            // 查询Y2并更新Y2
            if (StringUtils.isNotBlank(salesQuote.getEmployeeResponsiblePartyID())) {
                String y2Filter = "QuoteID eq '%s' and RoleCode eq 'ZY2'";
                c4cOdataFeign.getSalesQuotePartyCollection("ObjectID,QuoteID,PartyID,RoleCodeText", String.format(y2Filter, salesQuote.getId()), "json")
                        .getData().getResults().stream().findFirst()
                        .ifPresent(c4cY2Sales -> {
                            C4cY2OrY3Sales c4cY2OrY3Sales = new C4cY2OrY3Sales();
                            c4cY2OrY3Sales.setPartyID(salesQuote.getEmployeeResponsiblePartyID());
                            c4cOdataFeign.patchUpdateY2OrY3(c4cY2Sales.getObjectID(), c4cY2OrY3Sales);
                        });
            }
        }catch (Exception e){
            log.error("更新Y2失败，orderId：" + order.getId());
        }

        try{
            String businessPartnerId = sysUserService.getOMBySaleIds(order.getSalesId()).getBusinessPartnerId();
            if (StringUtils.isNotBlank(businessPartnerId)) {
                // 查询Y3并更新Y3
                String y3Filter = "QuoteID eq '%s' and RoleCode eq 'ZY3'";
                c4cOdataFeign.getSalesQuotePartyCollection("ObjectID,QuoteID,PartyID,RoleCodeText", String.format(y3Filter, salesQuote.getId()), "json")
                        .getData().getResults().stream().findFirst()
                        .ifPresent(c4cY2Sales -> {
                            C4cY2OrY3Sales c4cY2OrY3Sales = new C4cY2OrY3Sales();
                            c4cY2OrY3Sales.setPartyID(businessPartnerId);
                            c4cOdataFeign.patchUpdateY2OrY3(c4cY2Sales.getObjectID(), c4cY2OrY3Sales);
                        });
            }
        }catch (Exception e){
            log.error("更新Y3失败，orderId：" + order.getId());
        }
        order.setQuotationId(salesQuote.getId());
    }

    private C4cSalesQuote createSalesQuote(Order order) {
        // 报价单名
        String name = "CMS" + '-' + order.getDemanderName() + '-' + order.getContractNumber();
        EndUser demander = endUserService.getById(order.getDemanderId());
        // 获取联系人id
        String query = "AccountID eq '%s' and StatusCode eq '2'";
        C4cResponse<List<C4cGetContacts>> contacts = c4cOdataFeign.getContactCollection("ContactID,AccountID,Name,Email,Phone,Mobile", String.format(query, demander.getAccountId()), "json");

        // 报价单
        C4cSalesQuote salesQuote = new C4cSalesQuote();
        // 合同号
        salesQuote.setBuyerID(order.getContractNumber());
        // 报价单名
        salesQuote.setName(name);
        // soldto的c4cid
        salesQuote.setBuyerPartyID(demander.getAccountId());
        // 联系人id（根据接口查询获取第一个没有给空串）
        salesQuote.setBuyerContactPartyID(contacts.getData().getResults().stream().findFirst().map(C4cGetContacts::getContactID).orElse(""));
        // shipto的c4cId
        salesQuote.setProductRecipientPartyID(endUserService.getById(order.getShipToId()).getAccountId());
        // 所选销售的c4cid
        salesQuote.setEmployeeResponsiblePartyID(sysUserService.getById(order.getSalesId()).getBusinessPartnerId());
        // 合同号
        salesQuote.setPONumberKUT(order.getContractNumber());
        LocalDate submitDate = order.getSubmitTime() == null ? LocalDate.now() : order.getSubmitTime().toLocalDate();
        // 从提交到现在（预付）的天数
        int submitDateToNow = Math.toIntExact(ChronoUnit.DAYS.between(submitDate, LocalDate.now()));
        // 报价产品的最后一个到货时间 提交日期 + 交期（转为ISO格式）
        Optional.ofNullable(order.getSubmitTime()).ifPresent(submitTime -> {
            if (order.getDeliveryDate() != null) {
                LocalDateTime demanderSignedDate = submitTime.plusDays(order.getDeliveryDate() + submitDateToNow);
                salesQuote.setRequestedFulfillmentStartDateTime(demanderSignedDate.atZone(ZoneOffset.UTC).format(DateTimeFormatter.ISO_DATE_TIME));
            }
        });

        C4cSalesQuote result = c4cService.createSalesQuote(salesQuote);
        updateOrderAndItem(order, result.getId(), submitDateToNow);
        return result;
    }

    /**
     * 将c4c报价id更新到order中
     * 更新系统状态为c4c报价单已创建
     * 更新订单的交期（加上从提交到预付完的天数）
     * 更新订单行的交期（加上从提交到预付完的天数）
     * @param order 订单
     * @param salesQuoteId c4c报价id
     */
    private void updateOrderAndItem (Order order, String salesQuoteId, Integer submitDateToNow){

        int deliveryDate = order.getDeliveryDate() == null ? 0 : order.getDeliveryDate();

        orderService.lambdaUpdate()
                .eq(Order::getId, order.getId())
                .set(Order::getQuotationId, salesQuoteId)
                .set(Order::getSysStatus, OrderConstants.SysStatus.C4C_QUOTATION)
                .set(submitDateToNow != 0 && deliveryDate != 0, Order::getDeliveryDate, deliveryDate + submitDateToNow)
                .update();
        try {
            List<OrderItem> itemList = itemService.getByOrderId(order.getId());
            for (OrderItem orderItem : itemList) {
                LocalDateTime expectedDeliveryDate = orderItem.getExpectedDeliveryDate();
                if (expectedDeliveryDate != null) {
                    orderItem.setExpectedDeliveryDate(expectedDeliveryDate.plusDays(submitDateToNow));
                }
            }
            itemService.updateBatchById(itemList);
        }catch (Exception e){
            log.error("创建报价单后更新订单行交期失败，orderId：{}", order.getId());
        }
    }
}
